﻿using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using Xilium.CefGlue;
using Avalonia.Threading;
using Avalonia.ReactiveUI;
using System.Reflection;
using System.IO;


namespace CefGlue.Avalonia
{
    internal sealed class AvaloniaCefBrowserProcessHandler : CefBrowserProcessHandler
    {
        IDisposable _current;
        private object schedule = new object();

        protected override void OnScheduleMessagePumpWork(long delayMs)
        {
            lock (schedule)
            {
                if (_current != null)
                {
                    _current.Dispose();
                }

                if (delayMs <= 0)
                {
                    delayMs = 1;
                }

                _current = Observable.Interval(TimeSpan.FromMilliseconds(delayMs)).ObserveOn(AvaloniaScheduler.Instance).Subscribe((i) =>
                {
                    CefRuntime.DoMessageLoopWork();
                });
            }
        }

        protected override void OnBeforeChildProcessLaunch(CefCommandLine commandLine)
        {
            commandLine.AppendSwitch("default-encoding", "utf-8");
            commandLine.AppendSwitch("allow-file-access-from-files");
            commandLine.AppendSwitch("allow-universal-access-from-files");
            commandLine.AppendSwitch("disable-web-security");
            commandLine.AppendSwitch("ignore-certificate-errors");
            if (OperatingSystem.IsMacOS())
            {
                string avaloniatag = "avalonia-cef";
                if (!commandLine.HasSwitch(avaloniatag))
                {
                    commandLine.AppendSwitch(avaloniatag, "w");
                    //String subPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Assembly.GetEntryAssembly().FullName.Split(',')[0].Trim());
                    //Console.WriteLine($"SubProcessPath={subPath}");
                    //commandLine.SetProgram(subPath);
                }
            }
        }
    }
}
